package com.neo.tiny.demo.sso.controller;

import cn.hutool.core.util.StrUtil;
import com.neo.tiny.demo.sso.api.OauthApi;
import com.neo.tiny.demo.sso.common.ResResult;
import com.neo.tiny.demo.sso.dto.OAuth2AccessTokenRespDTO;
import com.neo.tiny.demo.sso.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 单点登录
 * @Author: yqz
 * @CreateDate: 2022/11/13 20:47
 */
@RestController
@RequestMapping("/auth")
public class SsoAuthController {

    @Autowired
    private OauthApi oauthApi;

    @PostMapping("/login-by-code")
    public ResResult<OAuth2AccessTokenRespDTO> loginByCode(@RequestParam("code") String code) {

        return oauthApi.postAccessToken(code);
    }

    /**
     * 使用刷新令牌，获得（刷新）访问令牌
     *
     * @param refreshToken 刷新令牌
     * @return 访问令牌；注意，实际项目中，最好创建对应的 ResponseVO 类，只返回必要的字段
     */
    @PostMapping("/refresh-token")
    public ResResult<OAuth2AccessTokenRespDTO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return oauthApi.refreshToken(refreshToken);
    }

    /**
     * 退出登录
     *
     * @param request 请求
     * @return 成功
     */
    @PostMapping("/logout")
    public ResResult<Boolean> logout(HttpServletRequest request) {
        String token = SecurityUtils.obtainHeaderToken(request);
        if (StrUtil.isNotBlank(token)) {
            return oauthApi.removeToken(token);
        }
        // 返回成功
        return new ResResult<>();
    }
}
